package cn.fastoo.common.service;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * oss服务类
 *
 */
@Component
public class OSSService {
	private String accessId = "LTAIJfSawIGYOZtG";
	private String accessKey = "ZVLwwHUE1knCq3NRNWRPJSr5h6z992";
	private String ossEndpoint ="http://oss-cn-hangzhou.aliyuncs.com";
	private String bucketName = "heijingwangluo-upload";

	private OSSClient client;

	private final static String PREFIX = "http://heijingwangluo-upload.oss-cn-hangzhou.aliyuncs.com/";

	/**
	 * 上传图片
	 * @param key
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public String uploadFile(String key, MultipartFile file) throws Exception {
		OSSClient client = getOSSClient();
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.getSize());
		objectMeta.setContentType(file.getContentType());
		objectMeta.setContentDisposition("inline");
		InputStream input = file.getInputStream();
		PutObjectResult result = client.putObject(bucketName, key, input,objectMeta);
		return PREFIX+key;
	}
	
	/**
	 * 上传图片
	 * @param key
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public String uploadFile(String key, InputStream is) throws IOException {
		OSSClient client = getOSSClient();
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(is.available());
		PutObjectResult result = client.putObject(bucketName, key, is,objectMeta);
		return PREFIX+key;
	}
 


	private OSSClient getOSSClient() {
		// 可以使用ClientConfiguration对象设置代理服务器、最大重试次数等参数。
		ClientConfiguration config = new ClientConfiguration();
		if (client == null) {
			client = new OSSClient(ossEndpoint, accessId, accessKey, config);
			// 创建bucket
			client.createBucket(bucketName);
			// 设置bucket的访问权限，public-read-write权限
			client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
		}
		return client;
	}

	
	 
}
